package com.lyj.sc.aliyuntianchi.test20220714;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: liyangjing
 * @Date: 2022/07/13/21:31
 * @Description:
 */
public class test3 {
    public List<List<Integer>> threeSum(int[] nums) {
        //双指针法
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            //因为排序过了，若大于0的话证明 没有和为0
            if(nums[i]>0){
                return list;
            }
            if(i>0 && nums[i]==nums[i-1]){
                continue;
            }
            //左
            int left= i+1;
            //右
            int right=nums.length-1;
            while (left<right){
                int sum = nums[i]+nums[left]+nums[right];
                if(sum>0){
                    right--;
                }else if(sum<0){
                    left++;
                }else{
                    list.add(Arrays.asList(nums[i],nums[right],nums[left]));

                    while(left<right && nums[left]==nums[left+1]) left++;

                    while (left<right && nums[right]==nums[right-1]) right--;

                    left++;
                    right--;
                }
            }
        }
        return list;
    }
}
